<template>
  <div class="home-container">
    <SideMenu />
    <div class="main-content">
      <!-- Sidebar -->
      <div class="settings-sidebar">
        <!-- Workspace Section -->
        <!-- Management Section -->
        <!-- <div class="section" v-if="isAdmin"> -->
        <div class="section" v-if="isAdmin">
          <div class="section-title text-left">
            {{ granary?.name ? `${granary.name} - 设置` : '知识库设置' }}
          </div>
          <div class="menu-items">
            <router-link :to="`/granary/config/basic?granary=${granary?.urn || ''}`" class="menu-item">
              <img src="@/assets/icon/document.png" class="menu-icon" />
              基本设置
            </router-link>
            <router-link :to="`/granary/config/datasource?granary=${granary?.urn || ''}`" class="menu-item">
              <img src="@/assets/icon/datasource.png" class="menu-icon" />
              数据源设置
            </router-link>
            <router-link :to="`/granary/config/chat?granary=${granary?.urn || ''}`" class="menu-item">
              <img src="@/assets/icon/debug.png" class="menu-icon" />
              测试
            </router-link>
          </div>
        </div>
      </div>

      <!-- Content Area -->
      <div class="content">
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import SideMenu from '@/components/SideMenu.vue'
import { useUserStore } from '@/store/user'
import { ref, onMounted,computed,watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter,useRoute } from 'vue-router'
import { CreateGranaryRequest,Granary,GetGranaryRequest, ListGranariesRequest, ListGranariesResponse, DeleteGranaryRequest, UpdateGranaryRequest } from "@/types/proto/api/v1/granary_service";
import { GetGranary } from "@/api/granary";
const userStore = useUserStore()
const isAdmin = computed(() => userStore.userInfo?.role === 'TENANT_ADMIN')
const router = useRouter()
const granary = ref<Granary | null>(null)
const route = useRoute()

const parseParamFromRoute = async () => {
  try {
      console.log("granary config parse param")
      const urn = route.query.granary
      let reload = true
      console.log("config granary urn:", urn)
      if (urn === null || urn === undefined) {
          granary.value = null
          reload = false
      } else if (granary.value != null) {
          if (granary.value.urn === urn) {
              console.log("granary config no need to reload")
              reload = false
          }
      }

      if (reload) {
          console.log("granary config reload for granary:", urn)
          let req = {urn:urn} as GetGranaryRequest
          let res = await GetGranary(req)
          granary.value = res
      }
      userStore.granary = granary.value
  } catch (error) {
      console.error('Error parsing granary config from route:', error)
  }
}

onMounted(() => {
  console.log("granary config on mounted")
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    router.push('/signin')
    return
  }

  if (userStore.granary != null) {
    granary.value = userStore.granary
  }
  parseParamFromRoute().then(() => {
      if (granary.value == null) {
        return
      }

      const ds = granary.value.sources
      if (ds == null || ds.length < 1) {
        router.push(`/granary/config/datasource?granary=${granary.value.urn}`)
      } else {
        router.push(`/granary/config/basic?granary=${granary.value.urn}`)
      }
  })
})

watch(() => route.query.granary, async (newUrn, oldUrn) => {
  console.log("granary change")
  if (newUrn !== oldUrn) {
    await parseParamFromRoute().then(() => {
      if (granary.value == null) {
        return
      }

      const ds = granary.value.sources
      if (ds == null || ds.length < 1) {
        router.push(`/granary/config/datasource?granary=${granary.value.urn}`)
      } else {
        router.push(`/granary/config/basic?granary=${granary.value.urn}`)
      }
  })
  }
})
</script>

<style scoped lang="scss">
.home-container {
  display: flex;
  max-width: 1440px;
  margin: 0 auto;
  min-height: 100vh;
}

.main-content {
  flex: 1;
  margin-left: 100px;
  display: flex;
  padding: 20px;
}

.settings-sidebar {
  width: 240px;
  background-color: #fff;
  padding: 20px;
  border-right: 1px solid #eee;
}

.workspace-section {
  margin-bottom: 32px;
}

.workspace-card {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 8px;
  margin-top: 8px;
}

.workspace-icon {
  width: 40px;
  height: 40px;
  background: #4080ff;
  color: white;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.workspace-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.workspace-name {
  font-size: 14px;
  color: #333;
}

.add-button {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #4080ff;
  cursor: pointer;
  font-size: 13px;
  
  i {
    font-size: 16px;
  }
}

.section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 13px;
  color: #999;
  margin-bottom: 12px;
  padding: 0 12px;
}

.menu-items {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 4px;
  color: #333;
  text-decoration: none;
  transition: all 0.2s;
  font-size: 14px;

  .menu-icon {
    width: 14px;
    height: 14px;
    margin-right: 8px;
  }

  &:hover {
    background-color: #f5f7fa;
  }

  &.router-link-active {
    background-color: #e8f3ff;
    color: #4080ff;

    .menu-icon {
      color: #4080ff;
    }
  }
}

.content {
  flex: 1;
  padding: 0 40px;
}

@media screen and (max-width: 1440px) {
  .home-container {
    max-width: 100%;
  }
}
</style>
